<!--
 * @Descripttion:
 * @version: 1.0.0
 * @Author: htang
 * @Date: 2023-11-08 19:47:14
 * @LastEditors: htang
 * @LastEditTime: 2023-11-09 21:07:48
-->
<template>
  <a-modal v-model:visible="visible" title="站点详情" :footer="false" class="amap-detail-modal" centered width="80%">
    <div class="detail-container p-4">
      <div class="flex items-center">
        <span class="tip">楼层旋转：</span>
        <a-select style="width: 230px" @focus="onFocusSelect" @blur="onBlurSelect">
          <a-select-option value="">请选择</a-select-option>
          <a-select-option value="">一层</a-select-option>
          <a-select-option value="">负一层</a-select-option>
        </a-select>
      </div>
      <div id="video-module">
        <div
          id="camera-play"
          :style="{
            width: videoParams.width + 'px',
            height: videoParams.height + 'px',
          }"
        ></div>
      </div>
      <div class="detail-tab">
        <ul class="flex items-center">
          <li class="flex items-center active">视频监控模块</li>
          <li class="flex items-center">传感器模块</li>
        </ul>
      </div>
      <div class="table-module">
        <a-table ref="cameraTable" :data-source="cameraDataSource" :columns="camearColumns" :scroll="{ y: 100 }" size="small" :pagination="false">
          <template v-slot:bodyCell="{ column, record, index }">
            <template v-if="column.dataIndex == 'action'">
              <a class="ico-play flex items-center justify-center">播放</a>
            </template>
          </template>
        </a-table>
      </div>
      <div class="table-module">
        <a-table ref="alarmTable" :data-source="alarmDataSource" :columns="alarmColumns" :scroll="{ y: 100 }" size="small" :pagination="false">
          <template v-slot:bodyCell="{ column, record, index }">
            <template v-if="column.dataIndex == 'action'">
              <a>查看</a>
            </template>
          </template>
        </a-table>
      </div>
    </div>
  </a-modal>
</template>

<script>
import { ref, watch, onMounted, defineComponent, onUnmounted, nextTick } from 'vue';
export default defineComponent({
  setup() {
    let visible = ref(false);

    let videoParams = ref({
      width: 0,
      height: 0,
    });

    // 摄像抢数据列表
    let cameraDataSource = ref([]);

    // 摄像抢列
    let camearColumns = ref([
      {
        title: '序号',
        align: 'center',
        dataIndex: 'tel',
      },
      {
        title: '摄像抢名称',
        align: 'center',
        dataIndex: 'tel',
      },
      {
        title: '设备状态',
        align: 'center',
        dataIndex: 'tel',
      },
      {
        title: '设备类型',
        align: 'center',
        dataIndex: 'tel',
      },
      {
        title: '最后截图时间',
        align: 'center',
        dataIndex: 'tel',
      },
      {
        title: 'IP地址',
        align: 'center',
        dataIndex: 'tel',
      },
      {
        title: '操作',
        dataIndex: 'action',
        align: 'center',
      },
    ]);

    // 报警列表
    let alarmDataSource = ref([]);

    // 报警列
    let alarmColumns = ref([
      {
        title: '序号',
        align: 'center',
        dataIndex: 'tel',
      },
      {
        title: '报警时间',
        align: 'center',
        dataIndex: 'tel',
      },
      {
        title: '站点名称',
        align: 'center',
        dataIndex: 'tel',
      },
      {
        title: '报警类型',
        align: 'center',
        dataIndex: 'tel',
      },
      {
        title: '操作',
        dataIndex: 'action',
        align: 'center',
      },
    ]);

    // 海康码
    let hikIndex = ref('44ef985343864cdfb7db5a99a10c2b40');

    let oWebControl;
    let initCount = 0;
    let pubKey = '';
    let uuid = '';
    // 0 播放，1回放
    let playMode = 0;
    let isPlay = ref(true);

    /**
     * 初始化插件
     */
    function initPlugin() {
      let playNode = document.getElementById('video-module');
      Object.assign(videoParams.value, {
        width: playNode?.clientWidth,
        height: playNode?.clientHeight,
      });
      console.log(videoParams.value);
      oWebControl = new WebControl({
        // 指定容器id
        szPluginContainer: 'camera-play',
        // 指定起止端口号，建议使用该值
        iServicePortStart: 15900,
        iServicePortEnd: 15909,
        // 用于IE10使用ActiveX的clsid
        szClassId: '23BF3B0A-2C56-4D97-9C03-0CB103AA8F11',
        cbConnectSuccess() {
          // 创建WebControl实例成功
          oWebControl
            .JS_StartService('window', {
              // WebControl实例创建成功后需要启动服务
              // 值"./VideoPluginConnect.dll"写死
              dllPath: './VideoPluginConnect.dll',
            })
            .then(
              () => {
                // 启动插件服务成功
                oWebControl.JS_SetWindowControlCallback({
                  // 设置消息回调
                  // oData 是封装的视频 web 插件回调消息的消息
                  cbIntegrationCallBack(oData) {
                    console.log(oData);
                  },
                });
                let { width, height } = videoParams.value;
                oWebControl.JS_CreateWnd('camera-play', width, height).then(() => {
                  // JS_CreateWnd创建视频播放窗口，宽高可设定
                  // 创建播放实例成功后初始化
                  init();
                });
              },
              () => {
                // 启动插件服务失败
              }
            );
        },
        cbConnectError() {
          // 创建WebControl实例失败
          oWebControl = null;
          isPlay.value = true;
          $('#camera-play').html('插件未启动，正在尝试启动，请稍候...');
          // 程序未启动时执行error函数，采用wakeup来启动程序
          WebControl.JS_WakeUp('VideoWebPlugin://');
          initCount++;
          if (initCount < 3) {
            setTimeout(() => {
              initPlugin();
            }, 3000);
          } else {
            isPlay.value = false;
            $('#camera-play').html(
              '<div>插件启动失败，请检查插件是否安装！' +
                "<a href='https://wrj-heneng.oss-cn-shenzhen.aliyuncs.com/voc/%E6%B5%B7%E5%BA%B7%E6%8F%92%E4%BB%B6/VideoWebPlugin.exe'>点击下载插件安装</a>" +
                '</div>'
            );
          }
        },
        cbConnectClose(bNormalClose) {
          // 异常断开：bNormalClose = false
          // JS_Disconnect正常断开：bNormalClose = true
          bNormalClose = true;
          // 关闭窗体
          oWebControl.JS_HideWnd();
          oWebControl.JS_Disconnect().then((res) => {
            console.log(res);
          });
          oWebControl = null;
        },
      });
    }

    function init() {
      getPubKey(() => {
        ////////////////////////////////// 请自行修改以下变量值	////////////////////////////////////
        //综合安防管理平台提供的appkey，必填"23182360"
        let appkey = '23182360';
        //综合安防管理平台提供的secret，必填
        let secret = setEncrypt('EsJuaYYpX7weX52ZYvIi');
        //综合安防管理平台IP地址，必填
        let ip = '202.104.29.139';
        //综合安防管理平台端口，若启用HTTPS协议，默认443
        const CAMERA_PORT = 443;
        let port = parseInt(CAMERA_PORT, 10);
        let snapDir = 'D:\\SnapDir'; //抓图存储路径
        let videoDir = 'D:\\VideoDir'; //紧急录像或录像剪辑存储路径
        let layout = '1x1'; //playMode指定模式的布局
        let enableHTTPS = 1; //是否启用HTTPS协议与综合安防管理平台交互，这里总是填1
        let encryptedFields = 'secret'; //加密字段，默认加密领域为secret
        let showToolbar = 0; //是否显示工具栏，0-不显示，非0-显示
        let showSmart = 1; //是否显示智能信息（如配置移动侦测后画面上的线框），0-不显示，非0-显示
        let buttonIDs = '0,16,256,257,258,259,260,512,513,514,515,516,517,768,769'; //自定义工具条按钮
        ////////////////////////////////// 请自行修改以上变量值	////////////////////////////////////

        oWebControl
          .JS_RequestInterface({
            funcName: 'init',
            argument: JSON.stringify({
              appkey, //API网关提供的appkey
              secret, //API网关提供的secret
              ip, //API网关IP地址
              //初始播放模式：0-预览，1-回放
              //播放模式（决定显示预览还是回放界面）
              playMode: playMode.value,
              port, //端口
              snapDir, //抓图存储路径
              videoDir, //紧急录像或录像剪辑存储路径
              layout, //布局
              enableHTTPS, //是否启用HTTPS协议
              encryptedFields, //加密字段
              showToolbar, //是否显示工具栏
              showSmart, //是否显示智能信息
              buttonIDs, //自定义工具条按钮
            }),
          })
          .then((oData) => {
            // 初始化后resize一次，规避firefox下首次显示窗口后插件窗口未与DIV窗口重合问题
            let { width, height } = videoParams.value;
            oWebControl.JS_Resize(width, height);
            window.addEventListener('resize', resizeWebControl);
          });
        previewVideo();
      });
    }

    //RSA加密
    function setEncrypt(value) {
      var encrypt = new JSEncrypt();
      encrypt.setPublicKey(pubKey);
      return encrypt.encrypt(value);
    }

    function resizeWebControl() {
      let playNode = document.getElementById('video-module');
      videoParams.value = {
        //浏览器当前窗口可视区域宽度
        width: playNode.clientWidth,
        //浏览器当前窗口可视区域高度
        height: playNode.clientHeight,
      };
      let { width, height } = videoParams.value;
      oWebControl.JS_Resize(width, height);
    }

    /**
     * 获取公钥
     */
    function getPubKey(callback) {
      oWebControl
        .JS_RequestInterface({
          funcName: 'getRSAPubKey',
          argument: JSON.stringify({
            keyLength: 1024,
          }),
        })
        .then(function (oData) {
          if (oData.responseMsg.data) {
            pubKey = oData.responseMsg.data;
            callback();
          }
        });
    }

    /**
     * 预览播放
     */
    function previewVideo() {
      // 获取输入的监控点编号值，必填
      let cameraIndexCode = hikIndex.value;
      // 主子码流标识：0-主码流，1-子码流
      let streamMode = 0;
      // 传输协议：0-UDP，1-TCP
      let transMode = 1;
      //是否启用GPU硬解，0-不启用，1-启用
      let gpuMode = 0;
      // 播放窗口序号（在2x2以上布局下可指定播放窗口）
      let wndId = -1;

      cameraIndexCode = cameraIndexCode.replace(/(^\s*)/g, '');
      cameraIndexCode = cameraIndexCode.replace(/(\s*$)/g, '');
      oWebControl.JS_RequestInterface({
        funcName: 'startPreview',
        argument: JSON.stringify({
          cameraIndexCode, //监控点编号
          streamMode, //主子码流标识
          transMode, //传输协议
          gpuMode, //是否开启GPU硬解
          wndId, //可指定播放窗口
        }),
      });
    }

    /**
     * 关闭海康插件
     */
    function closeWindow() {
      // 关闭窗体
      oWebControl.JS_HideWnd();
      oWebControl.JS_Disconnect();
    }

    onMounted(() => {
      // setTimeout(() => {
      //   visible.value = true;
      // }, 2000);
    });

    watch(
      () => visible.value,
      (flag) => {
        if (flag) {
          nextTick(() => {
            initPlugin();
          });
        } else {
          closeWindow();
        }
      }
    );

    /**
     * 下拉框获取焦点
     */
    function onFocusSelect(e) {
      // 参考：https://www.cnblogs.com/ymhweb/p/15650902.html
      nextTick(() => {
        oWebControl.JS_CuttingPartWindow(68, 0, 235, 260);
      });
    }

    /**
     * 下拉框失去焦点
     */
    function onBlurSelect(e) {
      oWebControl.JS_RepairPartWindow(68, 0, 235, 260);
    }

    return {
      visible,
      cameraDataSource,
      camearColumns,
      alarmDataSource,
      alarmColumns,
      videoParams,
      onFocusSelect,
      onBlurSelect,
    };
  },
});
</script>

<style lang="less" >
.amap-detail-modal {
  .ant-modal-content {
    background: rgba(0, 0, 0, 0.8);
    .ant-modal-close {
      .ant-modal-close-x {
        width: 27px;
        height: 27px;
        margin: 9px 20px;
        background: url('@/assets/images/img-16.png') no-repeat;
        cursor: pointer;
        .anticon {
          display: none;
        }
      }
    }
    .ant-modal-header {
      padding: 14.5px 40px;
      background: url('@/assets/images/img-35.png') no-repeat;
      background-size: 100% 100%;
      .ant-modal-title {
        color: #fff;
      }
    }
    .ant-modal-body {
      .detail-container {
        .tip {
          color: #fff;
        }
        #video-module {
          width: 100%;
          height: 346px;
          margin: 12px 0 0;
          #camera-play {
            width: 100%;
            height: 100%;
          }
        }
        .detail-tab {
          margin: 14px 0 6px;
          ul {
            padding: 0;
            margin: 0;
            li {
              font-size: 18px;
              cursor: pointer;
              color: #fff;
              &.active,
              &:hover {
                color: #19fcde;
                &::before {
                  background: url('@/assets/images/img-33.png') no-repeat;
                }
              }
              &::before {
                content: '';
                display: block;
                width: 6px;
                height: 24px;
                margin: 0 6px 0 0;
                background: url('@/assets/images/img-34.png') no-repeat;
              }
              &:first-child {
                padding: 0 20px 0 0;
                margin: 0 20px 0 0;
                border-right: 1px solid rgba(25, 252, 222, 0.2);
              }
            }
          }
        }
        .table-module {
          padding: 0 0 18px;
          margin: 18px;
          border-bottom: 1px solid rgba(25, 252, 222, 0.2);
          .ant-table-header {
            .ant-table-thead {
              tr {
                th {
                  background: #19fcde;
                  font-family: '阿里巴巴普惠体';
                  font-size: 14px;
                  color: #31373d;
                }
              }
            }
          }
          &:last-child {
            border: none;
          }
          .ico-play {
            &::before {
              content: '';
              display: block;
              width: 16px;
              height: 16px;
              margin: 0 5px 0 0;
              background: url('@/assets/images/img-37.png') no-repeat;
            }
            &:hover {
              color: rgba(25, 252, 222, 1);
              &::before {
                background: url('@/assets/images/img-38.png') no-repeat;
              }
            }
          }
        }
      }
    }
  }
}
</style>